from django.http import HttpResponse
from django.core.serializers import serialize
from django.core.cache import cache

from ...models.users import Users, UsersGroup
from ...models.chat_file_upload import ChatFiles
from ...models.chat_loginlog import LoginLog
from ...models.chat_history import ChatHistory
from ...models.chat_items import ChatItems
from ...models.chat_loginlog import LoginLog
from ...models.chat_orders import ChatOrders
from ...models.chat_redeem import Redeem
from ...models.dall_jobs import DallJob
from ...models.powerlogs import PowerLogs

from ...utils.data_handle import users_data_paging, loginlog_data_paging
from ...utils.users import generate_salt, create_password_hash

import json


def users_list(request):
    '''
    参数：username=&page=1&page_size=15
    '''
    chatuser_username_str = request.GET.get('username', None)
    chatuser_page_str = request.GET.get('page', 1)
    chatuser_page_size_str = request.GET.get('page_size', 20)

    if not chatuser_username_str:
        all_chatusers_obj = Users.objects.all().order_by('id')
        chatusers_tree_json = users_data_paging(all_chatusers_obj, chatuser_page_str, chatuser_page_size_str)
    else:
        one_chatusers_obj = Users.objects.filter(username=chatuser_username_str).order_by('id')
        chatusers_tree_json = users_data_paging(one_chatusers_obj, chatuser_page_str, chatuser_page_size_str)

    res_mes = {
        "code": 0,
        "data": chatusers_tree_json
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def users_save(request):
    '''
    save
    post
    body = {
            "id": 3,
            "username": "fanlichun",
            "nickname": "\"范立春\"",
            "avatar": "/media/uploads/2024/09/01/8293334042525704.png",
            "salt": "F7It8jTI",
            "power": 486,
            "chat_roles": [
                "gpt"
            ],
            "chat_models": [
                21,
                22,
                23,
                24
            ],
            "expired_time": "",
            "status": true,
            "last_login_at": 1725504143,
            "last_login_ip": "10.8.12.113",
            "vip": true,
            "chat_usersgroup": {
                "groupid": [
                    1,2
                ],
                "oldgroupid": [
                    1
                ]
            }
        }
    '''
    if request.method == 'POST':
        json_b = request.body
        # json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_b)

        # # 删除没必要的数据
        # # 前端已经做了这一步了
        # try:
        #     del json_obj['created_at']
        #     del json_obj['updated_at']
        #     del json_obj['salt']
        #     del json_obj['last_login_at']
        # except:
        #     pass

        # 查询数据
        if "id" in json_obj:
            chatusers_instance_list = Users.objects.filter(id=json_obj['id'])
            if chatusers_instance_list:
                chatusers_instance = chatusers_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            chatusers_instance_list = Users.objects.filter(username=json_obj['username'])
            if chatusers_instance_list:
                res_mes = {
                    "code": 1,
                    "message": "用户名已经被占用。已经有这个用户！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
            else:
                chatusers_instance = Users()

        # 保存数据
        for key, value in json_obj.items():
            if key == "nickname":
                if value:
                    nickname_str = json.dumps(value, ensure_ascii=False)
                    chatusers_instance.nickname = nickname_str
                else:
                    chatusers_instance.nickname = json_obj['username']
            elif key == "chat_roles":
                if value:
                    chatusers_instance.chat_roles_json = value
            elif key == "chat_models":
                if value:
                    chatusers_instance.chat_models_json = value
            elif key == "expired_time":
                if value:
                    chatusers_instance.expired_time = value
                else:
                    chatusers_instance.expired_time = None
            elif key == "password":
                # 有这个字段说明 是新增用户，需要单独的处理一下密码存储
                # 生成加密盐
                salt = generate_salt(8)
                pass_hash = create_password_hash(value, salt)
                chatusers_instance.salt = salt
                chatusers_instance.password = pass_hash
                chatusers_instance.last_login_at = None
            elif key == "chat_usersgroup":
                # 遇到这个key 先什么都不做，后面再处理
                groupid_list = value['groupid']
                if "oldgroupid" in value:
                    old_groupid_list = value['oldgroupid']
                else:
                    old_groupid_list = []
            else:
                code_str = "chatusers_instance.%s = '%s'" % (key, value)
                exec(code_str)

        # chatusers_instance.save()
        try:
            chatusers_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "保存数据失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        # 绑定用户绑定的用户组
        # 先获取所有的用户组实例
        # 这里代码抽时间需要简洁一下
        if old_groupid_list:
            # 如果不为空 是编辑用户
            difference_add = [i for i in groupid_list if not i in old_groupid_list]
            difference_del = [i for i in old_groupid_list if not i in groupid_list]
            if difference_add:
                # 新增绑定
                try:
                    for groupid in difference_add:
                        group_obj = UsersGroup.objects.get(id=groupid)
                        group_obj.users.add(chatusers_instance)
                except:
                    res_mes = {
                        "code": 1,
                        "message": "绑定用户组失败！用户创建成功！"
                    }
                    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                    return HttpResponse(res_mes_json)
            if difference_del:
                # 删除绑定
                try:
                    for groupid in difference_del:
                        group_obj = UsersGroup.objects.get(id=groupid)
                        group_obj.users.remove(chatusers_instance)
                except:
                    res_mes = {
                        "code": 1,
                        "message": "绑定用户组失败！用户创建成功！"
                    }
                    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                    return HttpResponse(res_mes_json)
        else:
            # 这里是新增用户 然后直接绑定用户组
            try:
                for groupid in groupid_list:
                    group_obj = UsersGroup.objects.get(id=groupid)
                    group_obj.users.add(chatusers_instance)
            except:
                res_mes = {
                    "code": 1,
                    "message": "绑定用户组失败！用户创建成功！"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)

        
        # 返回数据
        # 如果是新增用户的话 需要返回数据
        one_chatusers_obj = Users.objects.filter(username=json_obj['username']).order_by('id')
        chatusers_tree_json = users_data_paging(one_chatusers_obj, 1, 20)
        chatusers_mes = chatusers_tree_json['items'][0]

        # 设置用户信息缓存到redis
        cache.set("user_info_{}".format(chatusers_mes['id']), chatusers_tree_json["items"][0], timeout=3600)  # 设置缓存超时时间为3600秒

        if "id" in json_obj:
            res_mes = {
                "code": 0
            }
        else:
            res_mes = {
                "code": 0,
                "data": chatusers_mes
            }

        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def users_remove(request):
    re_id = request.GET.get('id')
    try:
        # 删除用户
        del_obj = Users.objects.get(id=re_id)
        del_obj.delete()

        # 删除用户关联的文件
        ChatFiles_del_obj = ChatFiles.objects.filter(user_id=re_id)
        ChatFiles_del_obj.delete()

        # 删除历史会话
        ChatHistory_del_obj = ChatHistory.objects.filter(user_id=re_id)
        ChatHistory_del_obj.delete()

        # 删除对话
        ChatItems_del_obj = ChatItems.objects.filter(user_id=re_id)
        ChatItems_del_obj.delete()

        # 删除登陆日志
        LoginLog_del_obj = LoginLog.objects.filter(user_id=re_id)
        LoginLog_del_obj.delete()

        # 删除订单信息
        ChatOrders_del_obj = ChatOrders.objects.filter(user_id=re_id)
        ChatOrders_del_obj.delete()

        # 删除卡密兑换记录
        Redeem_del_obj = Redeem.objects.filter(user_id=re_id)
        Redeem_del_obj.delete()

        # 删除绘画job数据
        DallJob_del_obj = DallJob.objects.filter(user_id=re_id)
        DallJob_del_obj.delete()

        # 删除算力日志数据
        PowerLogs_del_obj = PowerLogs.objects.filter(user_id=re_id)
        PowerLogs_del_obj.delete()


        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": "删除失败!"
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def users_resetpass(request):
    '''
    修改密码
    post
    body = {
        "username": "test5",
        "password": "123123123",
        "id": 9
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)


        chatusers_instance = Users.objects.get(id=json_obj['id'])
        chatusers_instance_salt = chatusers_instance.salt
        pass_hash = create_password_hash(json_obj['password'], chatusers_instance_salt)
        chatusers_instance.password = pass_hash

        try:
            chatusers_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": "修改密码失败！"
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    

def users_loginlog(request):
    '''
    GET
    获取登陆日志
    参数：page=1&page_size=15
    '''
    chatloginlog_page_str = request.GET.get('page', 1)
    chatloginlog_page_size_str = request.GET.get('page_size', 20)

    all_chatloginlog = LoginLog.objects.all().order_by('-id')
    chatloginlog_tree_json = loginlog_data_paging(all_chatloginlog, chatloginlog_page_str, chatloginlog_page_size_str)

    res_mes = {
        "code": 0,
        "data": chatloginlog_tree_json
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)

